<template>
  <div class="theme-content-item" style="position: relative;">
    <div class="padding-20px form-style">
      <div class="left-title">{{ title }}</div>
      <el-form ref="bankFormRef" label-width="120px" :model="form" :rules="rules"
        style="margin-top: 40px">
        <el-row style="display: flex;justify-content:start">
          <el-col :span="10">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="课程类型" prop="courseType">
              <el-cascader ref="courseTypeRef" v-model="form.courseType" placeholder="请选择课程类型" :options="data.courseList" @change="changeCourseHandle"
                           :props="{label:'name',value:'id',children:'children',emitPath:false}"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="类型" prop="type">
              <el-select clearable v-model="form.type" placeholder="请选择类型">
                <el-option v-for="item in data.bankTypeList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="关联建培圈内容" prop="assoBankId">
              <el-select clearable v-model="form.assoBankId" placeholder="请选择关联内容" @change="changeAssoBankHandle">
                <el-option v-for="item in data.assoBankList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="排序" prop="orderNum">
              <el-input type="number" v-model="form.orderNum" placeholder="请输入排序号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="状态" prop="publishedFlag">
              <el-radio v-model="form.publishedFlag" :label="1">上架</el-radio>
              <el-radio v-model="form.publishedFlag" :label="0">下架</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="说明">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入说明"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style=" position: fixed; bottom: 5%; left: 45%" class="flex-jc-s-b">
        <el-button size="small" @click="goBack()">
          <svg-icon icon-class="back" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">关 闭</span>
        </el-button>
        <el-button size="small" style="margin-left: 20px;" type="primary" @click="save">
          <svg-icon icon-class="save" class="el-input__icon input-icon" />
          <span style="margin-left: 5px;">保 存</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import {tableItem} from './const'
import {addBank, editBank, getBankDetail} from '@/api/resource/bank'
import {listDictItemByCode} from '@/api/config/dic'
import {listTeacher} from '@/api/teacher'
import {listDoc} from '@/api/resource/doc'
import {listAssoBank} from '../../../../api/resource/bank'
const { proxy } = getCurrentInstance();
const route = useRoute()
const router = useRouter()
const routeQuery = reactive(route.query)
const title = ref('');
const isAdd = ref(false);
const data = reactive({
  courseList: [],
  bankTypeList: [],
  teacherList: [],
  docList: [],
  assoBankList: []
})
const form = reactive({
  id: null,
  name: '',
  courseType: '',
  type: '',
  year: '',
  assoBankId: '',
  assoBankName: '',
  questionCount: '',
  assoCourseId: '',
  publishedFlag: 1,
  remark: '',
  courseTypeName: '',
  orderNum: ''
})

const rules = ({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  courseType: [{ required: true, message: '请选择课程类型', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
  assoBankId: [{ required: true, message: '请选择题库', trigger: 'blur' }],
  publishedFlag: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  orderNum: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
})

// 详情
const initDetail = (row) => {
  getBankDetail(row.id || route.query.id).then((res) => {
    let resData = res.data
    Object.keys(form).forEach((key) => { form[`${key}`] = resData[`${key}`] })
    let typeCode = form.type == 454 ? 'total' : 'practise'
    listAssoBank({levelNum: 2,courseName:form.courseTypeName,typeCode: typeCode}).then(res => {
      data.assoBankList = res.rows
    })
  })
}
const initData = () => {
  listDictItemByCode({typeCode: 'courseTypeCode'}).then(res => {
    data.courseList = res.rows
  })
  listDictItemByCode({typeCode: 'bankTypeCode'}).then(res => {
    data.bankTypeList = res.rows
  })
}

function changeCourseHandle() {
  data.assoBankList = []
  form.assoBankId = ''
  let courseTypeRef = proxy.$refs["courseTypeRef"]
  let pathLabels = courseTypeRef.getCheckedNodes()[0].pathLabels
  form.courseTypeName = pathLabels[0] + '-' +pathLabels[1]

  console.log(form.type)
  let typeCode = form.type == 454 ? 'total' : 'practise'
  listAssoBank({levelNum: 2,courseName:form.courseTypeName,typeCode: typeCode}).then(res => {
    data.assoBankList = res.rows
  })
}
function changeAssoBankHandle(val) {
  let selectedAssoBankItem = data.assoBankList.find(item => item.id == val)
  form.assoBankName = selectedAssoBankItem.name
  form.questionCount = selectedAssoBankItem.questionAmount
  form.assoCourseId = selectedAssoBankItem.courseId
}

const save = () => {
  proxy.$refs["bankFormRef"].validate(valid => {
    if (valid) {
      if (isAdd.value) {
        addBank(form).then(res => {
          if (res.code === 200) {
            clearForm()
            ElMessage.success('新增成功');
          }
        })
      } else {
        editBank(form).then(res => {
          if (res.code === 200) {
            ElMessage.success('修改成功');
          }
        })
      }
    }
  })
}
function goBack() {
  proxy.$tab.closeOpenPage();
  router.go(-1)
}
function clearForm() {
  Object.keys(form).forEach((key)=>{
    form[key] = ''
  })
  form.publishedFlag = 1
}

onMounted(() => {
  let titleMap = {
    add: '新增',
    edit: '修改',
  }
  routeQuery.type ? title.value = titleMap[routeQuery.type] : ''
  routeQuery.type == 'edit' ? initDetail(route.query) : ''
  isAdd.value = routeQuery.type == 'add'
  initData()
})
</script>
